package cn.hfuu.spark;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import java.util.Comparator;

public class WordCountWithSorting {
    public static void main(String[] args) {
        String filePath = "C:\\Users\\唐凤穎\\Desktop\\data.txt";
        Map<String, Integer> wordCountMap = new HashMap<>(); // 用于存储每个单词及其出现次数

        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = reader.readLine()) != null) {
                // 使用正则表达式分割单词
                String[] words = line.toLowerCase().split("\\W+");
                for (String word : words) {
                    if (!word.isEmpty()) {
                        wordCountMap.put(word, wordCountMap.getOrDefault(word, 0) + 1);
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 使用TreeMap和自定义比较器对单词出现次数进行降序排序
        Map<String, Integer> sortedWordCountMap = new TreeMap<>(new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                int countCompare = wordCountMap.get(o2).compareTo(wordCountMap.get(o1));
                if (countCompare != 0) {
                    return countCompare;
                } else {
                    return o1.compareTo(o2); // 如果出现次数相同，则按字母顺序排序
                }
            }
        });

        sortedWordCountMap.putAll(wordCountMap);

        // 输出排序后的单词及其出现次数
        sortedWordCountMap.forEach((word, count) -> System.out.println(word + ": " + count));
    }
}